from django.core.exceptions              import ImproperlyConfigured
from django.db                           import models
from django.utils.translation            import ugettext_lazy as _
from sitepal.sitebase.util               import iterappmodules
from sitepal.sitetheme.exceptions        import RendererDoesNotExist
from sitepal.sitetheme.models.containers import Container,ContainerManager
from sitepal.sitetheme.renderers         import RegionRenderer

class RegionManager(ContainerManager):
    def itermodules(self):
        return iterappmodules(submodule='siteapp.regions')

    def sync_object(self,name,data):
        created,obj = super(RegionManager,self).sync_object(name,data)
        try:
            renderer = data.get('renderer')
            if renderer:
                if issubclass(renderer,RegionRenderer):
                    obj.renderer_name = '.'.join((renderer.__module__,renderer.__name__))
                else:
                    raise ImproperlyConfigured,"Renderer must be a subclas of 'RegionRenderer'"
            return created,obj
        except Exception,e:
            raise ImproperlyConfigured,e

class Region(Container):
    renderer_name = models.CharField(_("region renderer name"),editable=False,max_length=250)
    objects       = RegionManager()

    class Meta(Container.Meta):
        verbose_name        = _('region')
        verbose_name_plural = _('regions')
        app_label           = 'sitetheme'

    @property
    def display_classes(self):
        return (u'region',) + tuple(super(Region,self).display_classes)

    @property
    def render_class(self):
        if self.renderer_name:
            return super(Region,self).render_class
        return RegionRenderer

